const express = require("express");
// const moment = require('moment')
const router = express.Router();
const db = require("../core/mysql");
const { forEach } = require("async");
router.post("/queryresume", async (req, res, next) => {
  let userId = req.body.userId;
  const sqlStr1 = `SELECT * FROM userdata WHERE userid=${userId}`;
  const sqlStr2 = `SELECT * FROM projectexplist WHERE projectId=${userId}`;
  const sqlStr3 = `SELECT * FROM workexplist WHERE workId=${userId}`;
  const existSql = `SELECT EXISTS(SELECT 1 FROM userdata WHERE userid = '${userId}') AS user_exists`;
  try {
    db.query(existSql, (err0, resulta) => {
      if (err0) res.json({ code: 500, msg: "查询失败" });
      console.log('-----------resulta',resulta);
      if (resulta[0].user_exists === 0){
        res.json({ code: 500, msg: "该用户ID未被注册，请点击注册" });
      }else if(resulta[0].user_exists === 1){
        db.query(sqlStr1, (err1, result1) => {
          if (err1) return res.json({ code: 500, msg: "请求数据失败" });
          db.query(sqlStr2, (err2, result2) => {
            if (err2) return res.json({ code: 500, msg: "请求数据失败" });
            db.query(sqlStr3, (err3, result3) => {
              if (err3) return res.json({ code: 500, msg: "请求数据失败" });
              res.json({
                code: 200,
                msg: "查询成功",
                data: {
                  ...result1[0],
                  projectExp: result2,
                  workerExp: result3,
                },
              });
            });
          });
        });
      }
    });
  } catch (error) {
    console.log("catch---------errror", error);
  }
});
router.post("/registId", async (req, res, next) => {
  let { userId } = req.body;
  if(!userId){res.json({ code: 500, msg: "注册失败,userId不能为空"});}
  const existSql = `SELECT EXISTS(SELECT 1 FROM userdata WHERE userid = '${userId}') AS user_exists`;
  db.query(existSql, (err, result) => {
    if (err) res.json({ code: 500, msg: "注册失败" });
    if (result[0].user_exists === 0) {
      // 新增
      const addSql1 = `INSERT INTO userdata (userid) VALUES ('${userId}')`;
      const addSql2 = `INSERT INTO projectexplist (projectId) VALUES ('${userId}')`;
      const addSql3 = `INSERT INTO workexplist (workId) VALUES ('${userId}')`;
      db.query(addSql1, (err1, result1) => {
        if (err1) res.json({ code: 500, msg: "注册失败" });
        db.query(addSql2, (err2, result2) => {
          if (err2) res.json({ code: 500, msg: "注册失败" });
          db.query(addSql3, (err3, result3) => {
            if (err3) res.json({ code: 500, msg: "注册失败" });
            res.json({ code: 200, msg: "注册成功" });
          });
        });
      });
    } else if (result[0].user_exists === 1) {
      res.json({ code: 200, msg: "该ID已存在，可直接查询" });
    }
  });
});
router.post("/addresume", async (req, res, next) => {
  let {
    userId,
    userName,
    gender,
    age,
    native,
    tel,
    emailAdress,
    serviceYears,
    jobIntention,
    desiredCity,
    personVerit,
    schoolName,
    schoolFloor,
    major,
    studyTime,
    workerExp,
    projectExp,
  } = req.body;
  console.log("-------useId", userId);
  const existSql = `SELECT EXISTS(SELECT 1 FROM userdata WHERE userid = '${userId}') AS user_exists`;
  db.query(existSql, (err, result) => {
    if (err) res.json({ code: 500, msg: "请求数据失败" });
    let operatSql;
    if (result[0].user_exists === 0) {
      // 新增
      operatSql = `INSERT INTO userdata (userId,userName,gender,age,native,tel,emailAdress,serviceYears,jobIntention,desiredCity,personVerit,schoolName,schoolFloor,major,studyTime) VALUES('${userId}','${userName}','${gender}','${age}','${native}','${tel}','${emailAdress}','${serviceYears}','${jobIntention}','${desiredCity}','${personVerit}','${schoolName}','${schoolFloor}','${major}','${studyTime}'); INSERT INTO projectexplist (projectId) VALUES ('${userId}'); INSERT INTO workexplist (workId) VALUES ('${userId}')`;
    } else if (result[0].user_exists === 1) {
      // 修改
      operatSql = `UPDATE userdata SET userName='${userName}', gender='${gender}', age='${age}', native='${native}', tel='${tel}', emailAdress='${emailAdress}', serviceYears='${serviceYears}', jobIntention='${jobIntention}', desiredCity='${desiredCity}', personVerit='${personVerit}', schoolName='${schoolName}', schoolFloor='${schoolFloor}', major='${major}', studyTime='${studyTime}'  WHERE userid='${userId}';`;
    }
    db.query(operatSql, (errAdd, resultAdd) => {
      if (errAdd) {
        res.json({ code: 500, msg: "操作失败" });
      } else {
        const workerSqls = workerExp.map((item, index) => {
          const workquery = `UPDATE workexplist SET cName ='${item.cName}', cProfession ='${item.cProfession}', cTime ='${item.cTime}',  workContent ='${item.workContent}',  workGrade ='${item.workGrade}' WHERE (id ='${item.id}' AND workId = '${userId}')`;
          return db.query(workquery);
        });
        const projectSqls = projectExp.map((item, index) => {
          const workquery = `UPDATE projectexplist SET projectName ='${item.projectName}', projectPost ='${item.projectPost}', projectTime ='${item.projectTime}',  projectTopic ='${item.projectTopic}',  projectContent ='${item.projectContent}',  projectContent ='${item.projectContent}', skillTags ='${item.skillTags}' WHERE (id ='${item.id}' AND projectId = '${userId}')`;
          return db.query(workquery);
        });
        Promise.all([...workerSqls, ...projectSqls])
          .then((suc) => {
            res.json({ code: 200, msg: "操作成功" });
          })
          .catch((errmise) => {
            res.json({ code: 500, msg: "操作失败" });
          });
      }
    });
  });
});
router.post("/addWorkExp", async (req, res, next) => {
  let { workId } = req.body;
  console.log("-----------workId-----", workId);
  const existSql = `SELECT EXISTS(SELECT 1 FROM userdata WHERE userid = '${workId}') AS user_exists`;
  db.query(existSql, (err, result) => {
    if (err)
      res.json({ code: 500, msg: "请确认用户ID已保存（点击底部保存按钮）" });
    if (result[0].user_exists === 1) {
      // 新增
      const addSql = `INSERT INTO workexplist (workId) VALUES('${workId}')`;
      db.query(addSql, (errAdd, resultAdd) => {
        if (errAdd) {
          res.json({ code: 500, msg: "插入失败" });
        } else {
          res.json({
            code: 200,
            msg: "新增成功",
            data: { id: resultAdd.insertId },
          });
        }
      });
    }
  });
});
router.post("/delWorkExp", async (req, res, next) => {
  let { userId, id } = req.body;
  const existSql = `SELECT EXISTS(SELECT 1 FROM userdata WHERE userid = '${userId}') AS user_exists`;
  db.query(existSql, (err, result) => {
    if (err)
      res.json({ code: 500, msg: "请确认用户ID已保存（点击底部保存按钮）" });
    if (result[0].user_exists === 1) {
      // 新增
      const addSql = `DELETE FROM workexplist WHERE id = '${id}'`;
      db.query(addSql, (errAdd, resultAdd) => {
        if (errAdd) res.json({ code: 500, msg: "删除失败" });
        res.json({ code: 200, msg: "删除成功" });
      });
    }
  });
});
router.post("/addProjextExp", async (req, res, next) => {
  let { projectId } = req.body;
  console.log("-----------projectId-----", projectId);
  const existSql = `SELECT EXISTS(SELECT 1 FROM userdata WHERE userid = '${projectId}') AS user_exists`;
  db.query(existSql, (err, result) => {
    if (err)
      res.json({ code: 500, msg: "新增项目经历失败" });
    if (result[0].user_exists === 1) {
      // 新增
      const addSql = `INSERT INTO projectexplist (projectId) VALUES('${projectId}')`;
      db.query(addSql, (errAdd, resultAdd) => {
        if (errAdd) {
          res.json({ code: 500, msg: "新增项目经历失败" });
        } else {
          res.json({
            code: 200,
            msg: "新增项目经历成功",
            data: { id: resultAdd.insertId },
          });
        }
      });
    }
  });
});
router.post("/delProjextExp", async (req, res, next) => {
  let { userId, id } = req.body;
  const existSql = `SELECT EXISTS(SELECT 1 FROM userdata WHERE userid = '${userId}') AS user_exists`;
  db.query(existSql, (err, result) => {
    if (err)
      res.json({ code: 500, msg: "请确认用户ID已保存（点击底部保存按钮）" });
    if (result[0].user_exists === 1) {
      // 新增
      const addSql = `DELETE FROM projectexplist WHERE id = '${id}'`;
      db.query(addSql, (errAdd, resultAdd) => {
        if (errAdd) {
          res.json({ code: 500, msg: "删除项目经历失败" });
        } else {
          res.json({ code: 200, msg: "删除项目经历成功" });
        }
      });
    }
  });
});
module.exports = router;
